package com.element.sentinel.execute;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.common.core.exception.BizException;
import com.common.core.exception.ExceptionFactory;
import com.common.core.exception.code.LimitErrorCode;

public class SentinelExecute {

    public static <T> T execute(String resourceName, SentinelInvoke<T> invoke) throws BizException {
        try (Entry ignored = SphU.entry(resourceName)) {
            return invoke.invoke();
        } catch (BlockException e) {
            throw ExceptionFactory.bizException(LimitErrorCode.A_API_LIMIT_ERROR);
        }
    }

    public interface SentinelInvoke<T> {

        /**
         * 执行限流的代码
         *
         * @return 返回值
         * @throws BlockException 限流异常
         */
        T invoke() throws BlockException;
    }
}